package com.lcf.gateway.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcf.base.model.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关全局异常捕获
 *
 * @author lcf
 */
@Configuration
public class GatewayGlobalExceptionHandler implements ErrorWebExceptionHandler {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final Logger log = LoggerFactory.getLogger(GatewayGlobalExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.error(ex.getMessage(), ex);

        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(R.fail());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(bytes)));
    }
}